﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using P2P.Network.ExtensionMethods;
using P2P.Client;
using P2P.DB.Model;
using P2P.DB;
using Newtonsoft.Json.Linq;
using P2P.Client.Model;

namespace P2P.Main.Handler
{
    public class BroadcastSearchHandler
    {
        private ApiProtocol apiProtocol;

        public BroadcastSearchHandler(ApiProtocol apiProtocol)
        {
            this.apiProtocol = apiProtocol;
        }

        public void BroadcastSearchFile() 
        {
            string searchTerm = (string)apiProtocol.Params["SearchTerm"];
            string searcherAccountId = (string)apiProtocol.Params["SearcherAccountId"];

            List<FileModel> files = SqliteHelper.GetDb().Queryable<FileModel>()
                .Where(it=>it.FileName.Contains(searchTerm)).ToList();

            string fileList = JsonConvert.SerializeObject(files);

            JObject data = new JObject();
            data.Add("Name", "BroadcastSearch");
            data.Add("Method", "FileSearchResultList");
            data.Add("Version", "1.0");

            JObject param = new JObject();
            param.Add("AccountId", SharedModel.Instance.AccountId);
            param.Add("FileList", fileList);
            param.Add("SearcherAccountId", searcherAccountId);
            data.Add("Params", param);

            string ack = JsonConvert.SerializeObject(data);

            apiProtocol.Socket.SendTo(ack,apiProtocol.RemoteEndPoint);
        }

        public void FileList() 
        {
        
        }
    }
}
